package com.piggy.common.core.utils.sms;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class AliSendSmsUtils {


	/**
	 * 使用AK&SK初始化账号Client
	 *
	 * @return Client
	 * @throws Exception
	 */
	public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
		Config config = new Config()
			// 您的AccessKey ID
			.setAccessKeyId(accessKeyId)
			// 您的AccessKey Secret
			.setAccessKeySecret(accessKeySecret);
		// 访问的域名
		config.endpoint = "dysmsapi.aliyuncs.com";
		return new Client(config);
	}


	//测试
	public static void main(String[] args_) throws Exception {
		Client client = AliSendSmsUtils.createClient("LTAI5tGmGfWAqVi8DucgrM68","0AiEsNjBT1bblW7eqNTSoGe4Vzxbp2");

		SendSmsRequest sendReq = new SendSmsRequest()
			.setPhoneNumbers("18501115509")
			.setTemplateCode("SMS_219555343")
			.setSignName("中云融拓")
			.setTemplateParam("{\"code\":\"1111\"}");
		// 复制代码运行请自行打印 API 的返回值
		SendSmsResponse sendResp = client.sendSms(sendReq);

		String code = sendResp.body.code;
		if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
			Console.log("错误信息: " + sendResp.body.message + "");
			return;
		}

		String bizId = sendResp.body.bizId;
		// 2. 等待 10 秒后查询结果
		com.aliyun.teautil.Common.sleep(10000);
		// 3.查询结果
		QuerySendDetailsRequest queryReq = new QuerySendDetailsRequest()
			.setPhoneNumber(com.aliyun.teautil.Common.assertAsString("18501115509"))
			.setBizId(bizId)
			.setSendDate(DateUtil.format(new Date(), "yyyyMMdd"))
			.setPageSize(10L)
			.setCurrentPage(1L);
		QuerySendDetailsResponse queryResp = client.querySendDetails(queryReq);
		java.util.List<QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO> dtos = queryResp.body.smsSendDetailDTOs.smsSendDetailDTO;
		// 打印结果
		for (QuerySendDetailsResponseBody.QuerySendDetailsResponseBodySmsSendDetailDTOsSmsSendDetailDTO dto : dtos) {
			if (com.aliyun.teautil.Common.equalString("" + dto.sendStatus + "", "3")) {
				Console.log("" + dto.phoneNum + " 发送成功，接收时间: " + dto.receiveDate + "");
			} else if (com.aliyun.teautil.Common.equalString("" + dto.sendStatus + "", "2")) {
				Console.log("" + dto.phoneNum + " 发送失败");
			} else {
				Console.log("" + dto.phoneNum + " 正在发送中...");
			}

		}
	}

}
